import axios from 'axios'
import {Toast} from 'vant'
import {baseUrl} from './env'

let instance = axios.create({
  timeout: 1000
})
const CODE_OK = 0

const active = {
  async request(options) {
    let method = options.method ? options.method.toUpperCase() : 'GET';
    if (!options.headers) options.headers = {}
    try {
      return await instance({
        baseURL: options.baseUrl || baseUrl,
        url: options.url,
        method: method,
        params: options.params, //params中的参数会拼接在url中，一般用于GET请求
        data: options.data, //data参数在方法体中
        headers: {
          'Accept': options.headers.accept || 'application/json',
          'Content-Type': options.headers.contentType || 'application/json',
          'provider': options.headers.provider || null,
          'token': options.headers.token || null,
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': 0,
        },
      });
    } catch (err) {
      console.error(err)
      return Promise.reject(err)
    }
  },

  async get(params) {
    if ((typeof params) === 'string') {
      params = {
        url: params
      }
    }
    return await this.request(params)
  },

  async post(params) {
    params.method = 'POST'
    return await this.request(params)
  },

  async put(params) {
    params.method = 'PUT'
    return await this.request(params)
  },

  async delete(params) {
    params.method = 'DELETE'
    return await this.request(params)
  },

  async uploadFile(params) {
    params.method = 'POST'
    params.headers.contentType = 'multipart/form-data'
    return await this.request(params)
  },
  //登出
  async logout() {
    let params = {
      url: '/logout'
    }
    await this.post(params)
    //清除app cookie
    console.log("登出成功");
    //跳转到登录页
    //if(this.$route.path != '/login')
    //this.redirectToLoginPage();
  }
}

// 拦截器的添加
// 请求拦截器
instance.interceptors.request.use(config => {
  // 发起请求前做些什么
  Toast.loading({
    mask: false,
    duration: 0,// 一直存在
    forbidClick: true, // 禁止点击
    message: '加载中...'
  })
  return config
}, () => {
  // 请求错误
  Toast.clear()
  Toast('请求错误，请求稍后重试')
})
// 响应拦截器
instance.interceptors.response.use(response => {
    Toast.clear()
    const res = response.data
    if (res.code === CODE_OK) {
      // 请求成功
      return res
    } else if (res.code === 998) {
      Toast('请先登录...');
      setTimeout(() => location.href = '/', 3000);
    } else if (res.code === 999) {
      Toast('您的账号已在其它地点登录，如非本人操作，请尽快修改密码');
      setTimeout(() => location.href = '/', 3000);
    } else if (res.code === 1000) {
      Toast('登录状态已经失效，请重新登录...');
      setTimeout(() => location.href = '/', 3000);
    } else if (res.code === 1005) {
      Toast(`没有权限访问！\n${res.msg}`);
    } else {
      Toast(res.msg);
    }
  }, err => {
    Toast.clear()
    Toast('请求错误，请求稍后重试')
    console.log(err)
  }
)

export default {
  request: active.request,
  get: active.get,
  post: active.post,
  put: active.put,
  delete: active.delete,
  uploadFile: active.uploadFile,
  logout: active.logout
}